package com.homedo.odin.solution.service.bizservice.personal;

import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.ObjectConverter;
import com.homedo.odin.solution.contract.pc.GetBrandFirmDetailReq;
import com.homedo.odin.solution.contract.personal.brandfirm.BrandFirmReq;
import com.homedo.odin.solution.enumcode.brand.FirmStatusEnum;
import com.homedo.odin.solution.enumcode.solution.SolutionStateEnum;
import com.homedo.odin.solution.enumcode.solution.SolutionTypeEnum;
import com.homedo.odin.solution.model.dto.UserSolutionCount;
import com.homedo.odin.solution.model.entity.BrandFirm;
import com.homedo.odin.solution.model.entity.BrandOwner;
import com.homedo.odin.solution.model.entity.UserBasic;
import com.homedo.odin.solution.model.entity.UserProfile;
import com.homedo.odin.solution.model.response.pc.brand.BrandFirmDetailResponseBean;
import com.homedo.odin.solution.service.BrandFirmServiceImpl;
import com.homedo.odin.solution.service.BrandOwnerServiceImpl;
import com.homedo.odin.solution.service.SolutionServiceImpl;
import com.homedo.odin.solution.service.UserBasicServiceImpl;
import com.homedo.odin.solution.service.UserProfileServiceImpl;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: zhaoxudong
 * @date: 2018/3/11 11:59
 * @Description:
 */
@Service
public class BrandFirmBizService {

    @Autowired
    BrandFirmServiceImpl brandFirmService;

    @Autowired
    UserProfileServiceImpl profileService;

    @Autowired
    SolutionServiceImpl solutionService;

    @Autowired
    BrandOwnerServiceImpl brandOwnerService;

    @Autowired
    UserBasicServiceImpl userBasicServiceImpl;

    @Autowired
    private UserProfileServiceImpl userProfileService;

    /**
     * 申请成为品牌商
     */
    @Transactional(rollbackFor = Exception.class)
    public void applyBrandFirm(BrandFirmReq request) {
        checkInput(request);
        //查用户
        UserBasic userBasic = userBasicServiceImpl.selectByUserId(request.getUserId());

        //查询用户下是否有品牌
        BrandFirm firm = brandFirmService.findFirmByUserIdAndSubmit(request.getUserId());
        BrandFirm brandFirm = new BrandFirm();
        //如果已有提交品牌，相当于编辑，否则相当于新增
        if (firm != null) {
            brandFirm = firm;
        }
        brandFirm.setUserId(request.getUserId());
        if(userBasic!=null){
            brandFirm.setUserName(userBasic.getUserName());
        }
        brandFirm.setBrandId(request.getBrandId());
        brandFirm.setBusinessLicense(request.getBusinessLicense());
        brandFirm.setContact(request.getContact());
        brandFirm.setContactMobile(request.getContactMobile());
        brandFirm.setContactEmail(request.getContactEmail());
        brandFirm.setFirmIcon(request.getFirmIcon());
        brandFirm.setFirmName(request.getFirmName());
        //如果上次存在，不能保存上次审核意见
        brandFirm.setAuditOpinion(" ");
        brandFirm.setStatus(FirmStatusEnum.AUDITING.getDbValue());
        brandFirm.setLastModifiedTime(new Date());
        brandFirmService.insertOrUpdate(brandFirm);
        //更新or新增用户userProfile表
        UserProfile profile = profileService.selectByUserId(request.getUserId());
        //userProfile是否存在
        boolean isExist = true;
        if (profile == null) {
            //新增
            isExist = false;
            profile = new UserProfile();
            profile.setCreatedBy(request.getUserId());
            profile.setUserId(request.getUserId());
        }
        // 申请时不需要更改用户头像
//        profile.setIcon(request.getFirmIcon());
        profile.setAddress(request.getAddress());
        if(userBasic!=null) {
            profile.setUserName(userBasic.getUserName());
        }
        profile.setModifiedBy(request.getUserId());
        profile.setModifiedTime(new Date());
        if (isExist) {
            profileService.updateById(profile);
        } else {
            profileService.insert(profile);
        }
    }

    /**
     * 校验参数
     */
    private void checkInput(BrandFirmReq request) {
        if (request.getUserId() == null || request.getUserId() <= 0) {
            throw new BizException(Meta.CODE_451.getCode(), "userId不符合规则");
        }
        if (request.getBrandId() == null || request.getBrandId() <= 0) {
            throw new BizException(Meta.CODE_451.getCode(), "品牌id不符合规则");
        }
        if (StringUtils.isBlank(request.getContact())) {
            throw new BizException(Meta.CODE_451.getCode(), "联系人不能为空");
        }
        if (StringUtils.isBlank(request.getContactMobile())) {
            throw new BizException(Meta.CODE_451.getCode(), "联系人手机号不能为空");
        }
        if (StringUtils.isBlank(request.getFirmName())) {
            throw new BizException(Meta.CODE_451.getCode(), "企业名称不能为空");
        }
        if (StringUtils.isBlank(request.getFirmIcon())) {
            throw new BizException(Meta.CODE_451.getCode(), "企业logo不能为空");
        }
        if (StringUtils.isBlank(request.getBusinessLicense())) {
            throw new BizException(Meta.CODE_451.getCode(), "营业执照不能为空");
        }
        if (StringUtils.isBlank(request.getAddress())) {
            throw new BizException(Meta.CODE_451.getCode(), "企业所在地不能为空");
        }

    }

    /**
     * PC_获取品牌商详情
     */
    public BrandFirmDetailResponseBean getBrandFirmDetail(GetBrandFirmDetailReq req, int userId) {
        BrandFirmDetailResponseBean resp = new BrandFirmDetailResponseBean();
        BrandFirm brandFirm = brandFirmService.getBrandFirmByUserId(userId);
//        if (userId > 0) {
//            brandFirm = brandFirmService.getBrandFirmByUserId(userId);
//        } else if (req.getBrandUid() > 0) {
//            brandFirm = brandFirmService.getBrandFirmByUserId(req.getBrandUid());
//        } else if (req.getBrandId() > 0) {
//            brandFirm = brandFirmService.findFirmByBrandId(req.getBrandId());
//        }  else {
//            throw new BizException(Meta.CODE_451.getCode(), "branduid和brandid不能同时为空");
//        }
        boolean notExists = brandFirm == null || ((null == req.getLoginUserId() || userId != req.getLoginUserId())
                && SolutionStateEnum.AUDITSUCCESS.getDbValue() != brandFirm.getStatus().intValue());
        if (notExists) {
            throw new BizException(Meta.CODE_451.getCode(), "该品牌厂商不存在");
        }
        resp = ObjectConverter.copyProperties(brandFirm, resp.getClass());
        UserProfile userProfile = userProfileService.findByUserId(userId);
        if (null != userProfile) {
            resp.setUserName(userProfile.getUserName());
            resp.setAddress(userProfile.getAddress());
        }

        if (req.isGetBrandOwner()) {
            BrandOwner brandOwner = brandOwnerService.getBrandOwnerById(resp.getBrandId());
            if (brandOwner != null) {
                resp.setBrandName(brandOwner.getBrandName());
                resp.setBrandIcon(brandOwner.getBrandIcon());
            }
        }
        if (req.isGetUserSolutionCount()) {
            UserSolutionCount count = null;
            if (brandFirm.getUserId().equals(userId)) {
                count = solutionService
                        .queryUserSolutionCount(brandFirm.getUserId(), 0, SolutionTypeEnum.BRAND_SOLUTION.getDbValue());
            } else {
                count = solutionService.queryUserSolutionCount(brandFirm.getUserId(), 30,
                        SolutionTypeEnum.BRAND_SOLUTION.getDbValue());
            }
            if (count != null && count.getTotal() > 0) {
                resp.setSolutionTotal(count.getTotal());
                resp.setSolutionViewTotal(count.getViewTotal() == null ? 0 : count.getViewTotal());
                resp.setSolutionDownloadTotal(count.getDownloadTotal() == null ? 0 : count.getDownloadTotal());
            }
        }
        return resp;

    }
}
